import {Table, Button, message, Modal} from 'antd'
// import Table from '../../_antd1.11.2/table'
// import Button from '../../_antd1.11.2/button'
// import Modal from '../../_antd1.11.2/modal'
// import message from '../../_antd1.11.2/message'

import * as API from './api'

import cloneDeep from 'lodash/cloneDeep'

let hide = null;

let ComEvent = {};

class Main extends React.Component {
    constructor(props) {
		super(props);
        this.state = {
            type:props.tableObj.type,
            tableShow:props.tableObj.tableShow || false,
            tableCount:0,
            tablePageNum:API.getLs("tablePageNum") || 10,
            tableDatas:[],
            stsData:{},
            tableLoading:false,
            tablePage:1,
            tableFixedLeft:props.tableObj.tableFixedLeft||"",
			tableFixedRight:props.tableObj.tableFixedRight||"",
            tableFixedHead:props.tableObj.tableFixedHead||0,
            tableExportShow:props.tableObj.tableExportShow || false,
            tableExportModal:false,
            tableExportPageNum:props.tableObj.tableExportPageNum || 10000,
            tableExportUrls:[],
            tableColumns:props.tableObj.columns || [],
            tableCheckbox:props.tableObj.tableCheckbox,
            tableThousand:props.tableObj.tableThousand||"",
            tableRowSel:[],
            sqlParams:props.tableObj.sqlParams,
            sumCloumns:props.tableObj.sumCloumns,
            isSts: props.tableObj.isSts || false
        }
    }
    componentDidUpdate() {
        //jQuery(".ant-checkbox-input").trigger("rbeauty");
    }
    componentDidMount() {
        //jQuery(".ant-checkbox-input").attr("_isBeauty",true);
        //console.log("jQuery.fn.tzCheckbox:",jQuery.fn.tzCheckbox());
        //removeBeatySwitch(jQuery(".ant-checkbox-input .jNiceHidden"));
        //jQuery.fn.tzCheckbox().removeBeatySwitch();
        //$.fn.tzCheckbox.removeBeatySwitch();
        const {type,sqlParams,tableColumns,tableShow,tablePageNum} = this.state;
        if(!tableShow) return ;
        let that = this;
        const outExcelOut = () => {
            //console.log("is in _xtable_getAllExcel ");
            that.setState({
                tableExportModal:true,
                tableExportUrls:[]
            });
            hide = message.loading('正在导出数据...', 0);
            that.doExport(1);
        }
        const outCheckbox = () => {
            const {tableRowSel} = that.state;
            return tableRowSel.join(",");
        }
        ComEvent.doExcelOutput = outExcelOut;
        ComEvent.doCheckIdsGet = outCheckbox;
        getAllExcelOut = outExcelOut;
        _xtable_getAllExcel = outExcelOut;
        _xtable_CheckedCheckboxId = outCheckbox;
        that.setState({
            tableLoading:true
        });
        API.doCountGet({
            type:type,
            sqlParams:JSON.stringify(sqlParams),
            columns:JSON.stringify(tableColumns)
        }).then((data)=>{
            if(!data.status) {
                message.error("表格数量获取失败！");
                return ;
            }
            //console.log("data.count:",data.count);
            that.setState({
                tableCount:data.count
            });
            //console.log("doCountGet:",data);
            return that.getDatas(1,tablePageNum);
        }).then((data)=>{
            //console.log("doDatasGet:",data);
            if(data.status) {
                that.setState({
                    tableDatas:data.datas,
                    stsData:data.sumCloumns,
                    isSts:data.isSts
                });
            }
            else {
                message.error("表格数据获取失败！");
            }
            that.setState({
                tableLoading:false
            });
        }).catch((msg)=>{
            that.setState({
                tableLoading:false
            });
            message.error("表格数据加载异常！");
        });
    }
    render() {
        let that = this;
        const {tableExportModal,tableExportUrls,tableColumns,tableExportShow,tablePageNum,tableRowSel,tableCheckbox} = this.state;
        const {tableShow,tableDatas,stsData,isSts,tableLoading,tableCount,tablePage,tableFixedLeft,tableFixedRight,tableFixedHead,tableThousand} = this.state;
        let width = 0;
        let noWidth = false;
        const tableFixedLeftArr = tableFixedLeft.split(",");
        const tableFixedRightArr = tableFixedRight.split(",");
        let columns = cloneDeep(tableColumns);
        columns = columns.map((column)=>{
            const realWidth = column.modeWidth?column.modeWidth*15:150;
			width += realWidth;
            if(tableFixedLeftArr.indexOf(column.dataIndex)>=0) {
                column.fixed = "left"
                column.width = realWidth;
            }
            else if(tableFixedRightArr.indexOf(column.dataIndex)>=0) {
                column.fixed = "right"
                column.width = realWidth;
            }
            else if(!noWidth) {
                noWidth = true;
            }
            else {
                column.width = realWidth;
            }
            if(!column.render) {
                //console.log("column:",column);
                let style = {};
                if(column.type=="3"&&column.htmltype=="1") {
                    style = {textAlign:"right"};
                    column.title = (
                        <div style={style}>{column.title}</div>
                    )
                }
                column.render = (text,record,index)=>{
                    return that.renderColumn(column,record,index,style,{tableThousand});
                }
            }
            return column;
        });
        //console.log("columns:",columns);
        const pagination = {
            total: tableCount,
            showSizeChanger: true,
            current:tablePage,
            pageSize:tablePageNum,
            pageSizeOptions:['10','20','50','100'],
            onShowSizeChange(current, pageSize) {
                //console.log("onShowSizeChange:",pageSize);
                API.setLs("tablePageNum",pageSize);
                that.setState({
                    tablePage:current,
                    tablePageNum:pageSize,
                    tableLoading:true
                });
                that.getDatas(current,pageSize).then((data)=>{
                    that.setState({
                        tableDatas:data.datas,
                        stsData:data.sumCloumns,
                        isSts:data.isSts,
                        tableLoading:false
                    });
                });
                //console.log('Current: ', current, '; PageSize: ', pageSize);
            },
            onChange(current) {
                that.setState({
                    tablePage:current,
                    tableLoading:true
                });
                that.getDatas(current,tablePageNum).then((data)=>{
                    that.setState({
                        tableDatas:data.datas,
                        stsData:data.sumCloumns,
                        isSts:data.isSts,
                        tableLoading:false
                    });
                });
                //console.log('Current: ', current);
            },
        };
        let rowSelection = {
            selectedRowKeys:tableRowSel,
            onChange:function(rsKeys) {
                //console.log("rsKeys:",rsKeys);
                that.setState({
                    tableRowSel:rsKeys
                });
            }
        };
        //console.log("tableCheckbox:",tableCheckbox);
        if(!tableCheckbox||tableDatas.length===0) rowSelection = null;
        //console.log("pagination:",pagination);
        //tableFixedHead
        let scroll = {x:width};
        if(tableFixedHead && tableFixedHead!="" && tableFixedHead!=0) {
            scroll.y = tableFixedHead;
        }
        //console.log("scroll:",scroll);
        return (
            <div style={{padding:10,width:"100%"}}>
                {tableExportShow && !tableShow && that.renderExportButton()}
                {tableExportShow && tableShow && <div style={{textAlign:"right",marginBottom:10}}>{that.renderExportButton()}</div>}
                {tableShow && <Table scroll={scroll} columns={columns} dataSource={tableDatas} isSts={isSts} stsData={stsData} size="middle" bordered loading={tableLoading} pagination={pagination} rowSelection={rowSelection} />}
                <Modal title="导出全部数据" visible={tableExportModal} closable={false}
                    onOk={()=>that.setState({tableExportModal:false})}
                    footer={[
                        <Button key="submit" type="primary" size="large" onClick={()=>that.setState({tableExportModal:false})}>
                        确 认
                        </Button>,
                    ]}>
                    <div style={{padding:20}}>
                        {
                            tableExportUrls && tableExportUrls.map((url,index)=>{
                                return (<a href={url} target="_blank" style={{marginRight:8}}>导出文件{index+1}</a>)
                            })
                        }
                    </div>
                </Modal>
            </div>
        )
    }
    renderColumn(column,record,index,style,config) {
		const value = record[column.dataIndex];
        let tt = config.tableThousand;
        tt = tt?tt.split(","):[];
        if(tt.indexOf(column.dataIndex)>=0) {
            return (
                <div style={style}>{API.formatNumber(value && parseFloat(value),2,1)}</div>
            )
        }
		let valueSpan = record[column.dataIndex+"span"];
		valueSpan = (valueSpan && valueSpan!="")?valueSpan:value;
        //console.log("valueSpan:",valueSpan);
        function createMarkup() { return {__html: valueSpan}; };
        return (
            <div style={style} dangerouslySetInnerHTML={createMarkup()} />
        )
	}
    renderExportButton() {
        let that = this;
        return (
            <Button onClick={()=>{
                that.setState({
                    tableExportModal:true,
                    tableExportUrls:[]
                });
                hide = message.loading('正在导出数据...', 0);
                that.doExport(1);
            }} size="small">导出全部</Button>
        )
    }
    getDatas(n,tablePageNum) {
        const {type,sqlParams,tableColumns,tableShow,sumCloumns} = this.state;
        // this.setState({
        //     tableDatas:[]
        // });
        //console.log("tablePageNum:",tablePageNum);
        return new Promise((resolve,reject)=>{
            API.doDatasGet({
                sumCloumns: sumCloumns,
                type:type,
                sqlParams:JSON.stringify(sqlParams),
                columns:JSON.stringify(tableColumns),
                min:tablePageNum===0?"":(n-1)*tablePageNum+1,
                max:tablePageNum===0?"":tablePageNum*n
            }).then((data)=>{
                if(!data.status) reject(data);
                else resolve(data);
            })
        });
    }
    doExport(n) {
        let that = this;
        const {type,sqlParams,tableColumns,tableExportModal,tableExportPageNum,sumCloumns} = this.state;
        API.doExport({
            sumCloumns: sumCloumns,
            type:type,
            sqlParams:JSON.stringify(sqlParams),
            columns:JSON.stringify(tableColumns),
            min:tableExportPageNum===0?"":(n-1)*tableExportPageNum+1,
            max:tableExportPageNum===0?"":tableExportPageNum*n
        }).then((data)=>{
            if(data.status) {
				let {tableExportUrls} = that.state;
                tableExportUrls.push(data.url);
                that.setState({
                    tableExportUrls:tableExportUrls
                });
                if(data.size==tableExportPageNum) {
	        		that.doExport(n+1);
	        	}
                else {
                    hide();
                    message.success("数据导出成功！");
                }
			}
			else {
                message.error('数据导出异常！');
            }
        });
    }
}

Main.doExcelOutput = ComEvent.doExcelOutput;
Main.doCheckIdsGet = ComEvent.doCheckIdsGet;

export default Main